﻿/*
 * @Author: Dreamy Icecream 
 * @Date: 2020-12-31 16:28:02 
 * @Description: 动态模糊
 * @Last Modified by: Dreamy Icecream
 * @Last Modified time: 2020-12-31 17:16:54
 */

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MotionBlur : PostEffectsBase {

    public Shader motionBlurShader;
    private Material motionBlurMaterial = null;
    public Material material {
        get {
            this.motionBlurMaterial = this.CheckShaderAndCreateMaterial (this.motionBlurShader, this.motionBlurMaterial);
            return this.motionBlurMaterial;
        }
    }

    /** 模糊程度 */
    [Range (0.0f, 0.9f)]
    public float blurAmount = 0.5f;

    private RenderTexture accumulationTexture;

    private void OnDisable () {
        DestroyImmediate (this.accumulationTexture);
    }

    private void OnRenderImage (RenderTexture src, RenderTexture dest) {
        if (this.material != null) {
            if (this.accumulationTexture == null ||
                this.accumulationTexture.width != src.width ||
                this.accumulationTexture.height != src.height
            ) {
                DestroyImmediate (this.accumulationTexture);
                this.accumulationTexture = new RenderTexture (src.width, src.height, 0);
                this.accumulationTexture.hideFlags = HideFlags.HideAndDontSave;
                Graphics.Blit (src, this.accumulationTexture);
            }

            this.accumulationTexture.MarkRestoreExpected ();

            this.material.SetFloat ("_BlurAmount", 1.0f - this.blurAmount);

            Graphics.Blit (src, accumulationTexture, this.material);
            Graphics.Blit (accumulationTexture, dest);

        } else {
            Graphics.Blit (src, dest);
        }
    }

}